 // UI操作和事件处理

// 更新代理服务器状态
function updateProxyServerStatus(running) {
    const statusEl = document.getElementById('proxy-server-status');
    const textEl = document.getElementById('proxy-server-text');
    const btnEl = document.getElementById('proxy-server-btn');

    if (running) {
        statusEl.className = 'status-item active';
        textEl.textContent = '运行中';
        btnEl.textContent = '停止';
        btnEl.className = 'btn danger';
    } else {
        statusEl.className = 'status-item inactive';
        textEl.textContent = '已停止';
        btnEl.textContent = '启动';
        btnEl.className = 'btn';
    }
}

// 更新系统代理状态
function updateSystemProxyStatus(status) {
    const statusEl = document.getElementById('system-proxy-status');
    const textEl = document.getElementById('system-proxy-text');
    const btnEl = document.getElementById('system-proxy-btn');

    const enabled = status.http_enabled || status.https_enabled;
    if (enabled) {
        statusEl.className = 'status-item active';
        textEl.textContent = '已启用';
        btnEl.textContent = '禁用';
        btnEl.className = 'btn danger';
    } else {
        statusEl.className = 'status-item inactive';
        textEl.textContent = '已禁用';
        btnEl.textContent = '启用';
        btnEl.className = 'btn';
    }
}

// 显示规则列表
function displayRules(rules) {
    const listEl = document.getElementById('rules-list');
    listEl.innerHTML = '';

    rules.forEach((rule, index) => {
        const ruleEl = document.createElement('div');
        
        // 确定规则类型和状态
        const isMockRule = rule.type === 'mock' || rule.mock_response;
        const isEnabled = rule.enabled !== false; // 默认启用
        
        ruleEl.className = 'rule-item';
        if (isMockRule) ruleEl.classList.add('mock');
        if (!isEnabled) ruleEl.classList.add('disabled');
        
        // 构建显示内容
        let targetText = '';
        if (isMockRule) {
            const mockResponse = rule.mock_response || {};
            const status = mockResponse.status || 200;
            const contentType = mockResponse.content_type || 'application/json';
            const hasFile = mockResponse.content_file;
            const dataSource = hasFile ? `文件: ${mockResponse.content_file}` : '内联内容';
            targetText = `Mock响应 (${status}, ${contentType}) - ${dataSource}`;
        } else {
            const target = rule.target || {};
            targetText = `${target.scheme || 'http'}://${target.host || 'localhost'}:${target.port || 80}`;
            const stripText = rule.strip_prefix ? ` (去除前缀: ${rule.strip_prefix})` : '';
            targetText += stripText;
        }
        
        // 规则类型和状态标签
        const typeLabel = isMockRule ? '<span class="rule-type mock">Mock</span>' : '<span class="rule-type proxy">代理</span>';
        const statusLabel = isEnabled ? '<span class="rule-status enabled">启用</span>' : '<span class="rule-status disabled">禁用</span>';
        const patternType = rule.pattern_type || 'string';
        const patternTypeLabel = `<span class="rule-pattern-type ${patternType}">${patternType === 'regex' ? 'REGEX' : 'STRING'}</span>`;
        
        ruleEl.innerHTML = `
            <div class="rule-info">
                <div class="rule-pattern">
                    ${rule.pattern}
                    ${patternTypeLabel}
                    ${typeLabel}
                    ${statusLabel}
                </div>
                <div class="rule-target">${targetText}</div>
            </div>
            <div class="rule-actions">
                <button class="btn btn-small ${isEnabled ? 'danger' : 'success'}" onclick="toggleRuleEnabled(${index})">${isEnabled ? '禁用' : '启用'}</button>
                <button class="btn btn-small" onclick="editRule(${index})">编辑</button>
                <button class="btn btn-small danger" onclick="deleteRule(${index})">删除</button>
            </div>
        `;
        
        listEl.appendChild(ruleEl);
    });
}

// 显示添加规则模态框
function showAddRuleModal() {
    currentEditIndex = -1;
    document.getElementById('modal-title').textContent = '添加规则';
    document.getElementById('rule-form').reset();
    document.getElementById('rule_type').value = 'proxy';
    document.getElementById('pattern_type').value = 'string';
    document.getElementById('enabled').value = 'true';
    toggleRuleTypeFields();
    togglePatternTypeFields();
    document.getElementById('rule-modal').style.display = 'block';
}

// 切换规则类型字段显示
function toggleRuleTypeFields() {
    const ruleType = document.getElementById('rule_type').value;
    const proxyFields = document.getElementById('proxy-fields');
    const mockFields = document.getElementById('mock-fields');
    
    if (ruleType === 'mock') {
        proxyFields.style.display = 'none';
        mockFields.style.display = 'block';
        // Mock规则不需要host和port为必填
        document.getElementById('host').removeAttribute('required');
        document.getElementById('port').removeAttribute('required');
    } else {
        proxyFields.style.display = 'block';
        mockFields.style.display = 'none';
        // 代理规则需要host和port为必填
        document.getElementById('host').setAttribute('required', '');
        document.getElementById('port').setAttribute('required', '');
    }
}

// 切换Mock数据源字段显示
function toggleMockDataFields() {
    const dataSource = document.getElementById('mock_data_source').value;
    const inlineField = document.getElementById('mock-inline-field');
    const fileField = document.getElementById('mock-file-field');
    
    if (dataSource === 'file') {
        inlineField.style.display = 'none';
        fileField.style.display = 'block';
    } else {
        inlineField.style.display = 'block';
        fileField.style.display = 'none';
    }
}

// 隐藏规则模态框
function hideRuleModal() {
    document.getElementById('rule-modal').style.display = 'none';
}

// 显示日志
function displayLogs(logs) {
    const logContent = document.getElementById('log-content');
    
    if (logs.length === 0) {
        logContent.innerHTML = '<div class="log-empty">没有找到匹配的日志</div>';
        return;
    }
    
    logContent.innerHTML = '';
    
    logs.forEach(log => {
        const logEntry = document.createElement('div');
        logEntry.className = `log-entry level-${log.level || 'INFO'}`;
        
        logEntry.innerHTML = `
            <div class="log-time">${log.timestamp || ''}</div>
            <div class="log-level ${log.level || 'INFO'}">${log.level || 'INFO'}</div>
            <div class="log-message">${escapeHtml(log.message || '')}</div>
        `;
        
        logContent.appendChild(logEntry);
    });
}

// 清除日志过滤器
function clearLogFilters() {
    document.getElementById('log-rule-filter').value = '';
    document.getElementById('log-level-filter').value = '';
    document.getElementById('log-date-filter').value = '';
    loadLogs();
}

// 生成手动安装步骤
function generateManualSteps() {
    const manualSteps = document.getElementById('manual-steps');
    const userAgent = navigator.userAgent;
    let steps = '';
    
    if (userAgent.includes('Mac')) {
        steps = `
            <h5>🍎 macOS 手动安装步骤:</h5>
            <ol>
                <li>双击证书文件打开钥匙串访问</li>
                <li>选择"系统"钥匙串</li>
                <li>找到"mitmproxy"证书，双击打开</li>
                <li>展开"信任"部分</li>
                <li>将"使用此证书时"设置为"始终信任"</li>
                <li>关闭窗口并输入密码确认</li>
            </ol>
        `;
    } else if (userAgent.includes('Windows')) {
        steps = `
            <h5>🪟 Windows 手动安装步骤:</h5>
            <ol>
                <li>以管理员身份运行命令提示符</li>
                <li>执行命令: <code>certutil -addstore -f Root "证书文件路径"</code></li>
            </ol>
            <p>或者:</p>
            <ol>
                <li>双击证书文件</li>
                <li>点击"安装证书"</li>
                <li>选择"本地计算机"</li>
                <li>选择"将所有证书都放入下列存储"</li>
                <li>选择"受信任的根证书颁发机构"</li>
                <li>完成安装</li>
            </ol>
        `;
    } else {
        steps = `
            <h5>🐧 Linux 手动安装步骤:</h5>
            <ol>
                <li>复制证书到系统目录:<br>
                    <code>sudo cp ~/.mitmproxy/mitmproxy-ca-cert.pem /usr/local/share/ca-certificates/mitmproxy-ca-cert.crt</code>
                </li>
                <li>更新证书存储:<br>
                    <code>sudo update-ca-certificates</code>
                </li>
            </ol>
        `;
    }
    
    manualSteps.innerHTML = steps;
}

function copyToClipboard(text, buttonElement) {
    navigator.clipboard.writeText(text).then(() => {
        // 临时改变按钮文本
        const button = buttonElement || event.target;
        const originalText = button.textContent;
        button.textContent = '已复制!';
        setTimeout(() => {
            button.textContent = originalText;
        }, 2000);
    }).catch(err => {
        console.error('复制失败:', err);
        alert('复制失败，请手动复制');
    });
}

function openCertDirectory() {
    // 这个功能需要后端支持，暂时显示路径
    alert('证书目录路径: ~/.mitmproxy/\n\n请在文件管理器中打开此路径');
}

// 正则表达式相关功能

// 切换匹配类型字段显示
function togglePatternTypeFields() {
    const patternType = document.getElementById('pattern_type').value;
    const regexTools = document.getElementById('regex-tools');
    const patternInput = document.getElementById('pattern');
    
    if (patternType === 'regex') {
        regexTools.style.display = 'block';
        patternInput.placeholder = '例如: ^https?://api\\.example\\.com/.*';
    } else {
        regexTools.style.display = 'none';
        patternInput.placeholder = '例如: api.example.com';
    }
    
    // 清除测试结果
    const testResult = document.getElementById('regex-test-result');
    testResult.innerHTML = '';
    testResult.className = 'regex-test-result';
}

// 插入正则表达式模板
function insertRegexTemplate(template) {
    const patternInput = document.getElementById('pattern');
    patternInput.value = template;
    patternInput.focus();
}

// 测试正则表达式匹配
function testRegexPattern() {
    const pattern = document.getElementById('pattern').value;
    const testUrl = document.getElementById('regex-test-url').value;
    const patternType = document.getElementById('pattern_type').value;
    const resultDiv = document.getElementById('regex-test-result');
    
    if (!pattern) {
        showTestResult('请输入匹配模式', 'error');
        return;
    }
    
    if (!testUrl) {
        showTestResult('请输入测试URL', 'error');
        return;
    }
    
    // 调用API测试匹配
    fetch('/api/regex/test', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            pattern: pattern,
            test_url: testUrl,
            pattern_type: patternType
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            if (data.matched) {
                let message = `✅ 匹配成功 (${data.pattern_type})`;
                if (data.match_info && data.match_info.full_match) {
                    message += `<br>匹配内容: "${data.match_info.full_match}"`;
                    if (data.match_info.groups && data.match_info.groups.length > 0) {
                        message += `<br>捕获组: [${data.match_info.groups.join(', ')}]`;
                    }
                }
                showTestResult(message, 'success');
            } else {
                showTestResult(`❌ 不匹配 (${data.pattern_type})`, 'no-match');
            }
        } else {
            showTestResult(`❌ 测试失败: ${data.error}`, 'error');
        }
    })
    .catch(error => {
        showTestResult(`❌ 网络错误: ${error.message}`, 'error');
    });
}

// 显示测试结果
function showTestResult(message, type) {
    const resultDiv = document.getElementById('regex-test-result');
    resultDiv.innerHTML = message;
    resultDiv.className = `regex-test-result ${type}`;
}